{% extends "admin/base.html" %}

{% block stylesheets %}
	<link rel="stylesheet" type="text/css" href="{{ request.script_root }}/themes/admin/static/css/vendor/codemirror.min.css">
	<style>
	.CodeMirror-gutters {
		min-height: 100% !important;;
	}
	</style>
{% endblock %}

{% block content %}

<div id="media-modal" class="modal fade" tabindex="-1">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<div class="modal-header">
				<div class="container">
					<div class="row">
						<div class="col-md-12">
							<h3 class="text-center">Media Library</h3>
						</div>
					</div>
				</div>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<div class="modal-header">
					<div class="container">
						<div class="row mh-100">
							<div class="col-md-8" id="media-library-list">
							</div>
							<div class="col-md-4">
								<h4 class="text-center">Media Details</h4>
								<div id="media-item">
									<div class="text-center" id="media-icon">
									</div>
									<br>
									<div class="text-center" id="media-filename">
									</div>
									<br>
									<div class="form-group">
										Link: <input class="form-control" type="text" id="media-link" readonly>
									</div>

									<div class="form-group text-center">
										<button class="btn btn-success w-100" id="media-insert">Insert</button>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>

				<form id="media-library-upload">
					<div class="form-group">
						<label for="media-files">
							Upload Files
						</label>
						<input type="file" name="files[]" id="media-files" class="form-control-file" multiple>
						<sub class="help-block">
							Attach multiple files using Control+Click or Cmd+Click.
						</sub>
					</div>
					<input type="hidden" value="{{ nonce }}" name="nonce" id="nonce">
				</form>

			</div>
			<div class="modal-footer">
				<div class="float-right">
					<button type="submit" class="btn btn-primary" onclick="uploadfiles();">Upload</button>
				</div>

			</div>
		</div>
	</div>
</div>


<div class="container">
	<div class="row pt-5">
		<div class="col-md-12">
			<div class="row">
			{% for error in errors %}
				<div class="large-12 large-centered columns">
					<div data-alert class="alert-box alert centered text-center">
						<span>{{ error }}</span>
						<a href="#" class="close">×</a>
					</div>
				</div>
			{% endfor %}
			</div>

			<form id="page-edit" method="POST">
				<div class="form-group">
					<div class="col-md-12">
						<h3>Title</h3>
						<p class="text-muted">This is the title shown on the navigation bar</p>
						<input class="form-control radius" id="route" type="text" name="title"
							   value="{% if page is defined %}{{ page.title }}{% endif %}" placeholder="Title">
					</div>
				</div>

				<div class="form-group">
					<div class="col-md-12">
						<h3>Route</h3>
						<p class="text-muted">This is the URL route that your page will be at (e.g. /page). You can also enter links to link to that page.</p>
						<input name='nonce' type='hidden' value="{{ nonce }}">
						<input class="form-control radius" id="route" type="text" name="route" value="{% if page is defined %}{{ page.route }}{% endif %}" placeholder="Route">

						<div class="form-check">
							<label class="form-check-label float-right">
								<input class="form-check-input" type="checkbox" name="auth_required" {% if page is defined and page.auth_required %}checked{% endif %}>
								Users must be logged in to see this page
							</label>
						</div>

					</div>
				</div>

				<div class="form-group">
					<div class="col-md-12">

						<h3>Content</h3>
						<p class="text-muted">This is the HTML content of your page</p>

						<ul class="nav nav-tabs" role="tablist" id="content-edit">
							<li class="nav-item" role="presentation" class="active">
								<a class="nav-link active" href="#content-write" aria-controls="home" role="tab" data-toggle="tab">Write</a>
							</li>
							<li class="nav-item" role="presentation">
								<a class="nav-link" onclick="preview_page(); return true;" href="#"">Preview</a>
							</li>
						</ul>

						<div class="tab-content">
							<div role="tabpanel" class="tab-pane active" id="content-write" style="height:400px">
								<br>

								<div class="form-inline">
									<div class="btn-group btn-group-sm">
										<div class="btn-group">
											<button type="button" class="btn btn-primary" id="media-button">
												<i class="fas fa-camera-retro"></i>
												Media Library
											</button>
										</div>
									</div>
								</div>

								<br>

								<div class="form-group">
									<textarea id="admin-pages-editor" class="d-none" name="html">{% if page is defined %}{{ page.html }}{% endif %}</textarea>
									<input name='id' type='hidden' {% if page is defined %}value="{{ page.id }}"{% endif %}>
								</div>
							</div>
							<div role="tabpanel" class="tab-pane content" id="content-preview" style="height:400px">
							</div>
						</div>
					</div>
				</div>

				<div class="form-group float-right">
					<button class="btn btn-success" id="publish-page">
						Publish
					</button>
					<button class="btn btn-primary" id="save-page">
						{% if page is defined %}
							Update
						{% else %}
							Save
						{% endif %}
					</button>
				</div>

			</form>
		</div>
	</div>
</div>
{% endblock %}

{% block scripts %}
<script src="{{ request.script_root }}/themes/admin/static/js/utils.js"></script>
<script src="{{ request.script_root }}/themes/admin/static/js/vendor/codemirror.min.js"></script>
<script>
	var editor = CodeMirror.fromTextArea(document.getElementById("admin-pages-editor"), {
		lineNumbers: true,
		lineWrapping: true,
		mode: "xml",
		htmlMode: true,
	});


	function uploadfiles(){
		var form = $('#media-library-upload')[0];
		var formData = new FormData(form);
		console.log(formData);
		$.ajax({
			url: script_root + '/admin/media',
			data: formData,
			type: 'POST',
			cache: false,
			contentType: false,
			processData: false,
			success: function(data){
				refreshfiles(data);
				form.reset();
			}
		});
	}

	function refreshfiles(data){
		var data = data.results;
		var list = $('#media-library-list');
		var mapping = {
			// Image Files
			'png': 'fa-file-image',
			'jpg': 'fa-file-image',
			'jpeg': 'fa-file-image',
			'gif': 'fa-file-image',
			'bmp': 'fa-file-image',
			'svg': 'fa-file-image',

			// Text Files
			'txt': 'fa-file-alt',

			// Video Files
			'mov': 'fa-file-video',
			'mp4': 'fa-file-video',
			'wmv': 'fa-file-video',
			'flv': 'fa-file-video',
			'mkv': 'fa-file-video',
			'avi': 'fa-file-video',

			// PDF Files
			'pdf': 'fa-file-pdf',

			// Audio Files
			'mp3': 'fa-file-sound',
			'wav': 'fa-file-sound',
			'aac': 'fa-file-sound',

			// Archive Files
			'zip': 'fa-file-archive',
			'gz': 'fa-file-archive',
			'tar': 'fa-file-archive',
			'7z': 'fa-file-archive',
			'rar': 'fa-file-archive',

			// Code Files
			'py': 'fa-file-code',
			'c': 'fa-file-code',
			'cpp': 'fa-file-code',
			'html': 'fa-file-code',
			'js': 'fa-file-code',
			'rb': 'fa-file-code',
			'go': 'fa-file-code',
		};
		for (var i = 0; i < data.length; i++) {
			var f = data[i];
			var ext = f.location.split('.').pop();
			var fname = f.location.split('/')[1];

			var wrapper = $('<div>').attr('class', 'media-item-wrapper');

			var link = $('<a>');
			link.attr('href', '##');

			if (mapping[ext] == undefined)
				link.append('<i class="far fa-file" aria-hidden="true"></i> '.format(mapping[ext]));
			else
				link.append('<i class="far {0}" aria-hidden="true"></i> '.format(mapping[ext]));

            link.append($('<small>').attr('class', 'media-item-title').text(fname));

			link.click(function(e){
				var media_div = $(this).parent();
				var icon = $(this).find('.svg-inline--fa')[0];
				var f_loc = media_div.attr('data-location');
				var fname = media_div.attr('data-filename');
				$('#media-link').val(f_loc);
				$('#media-filename').html(
				    $('<a>').attr('href', f_loc).attr('target', '_blank').text(fname)
				);

				$('#media-icon').empty();
				if ($(icon).hasClass('fa-file-image')){
					$('#media-icon').append($('<img>').attr('src', f_loc).css({'max-width':'100%', 'max-height': '100%', 'object-fit': 'contain'}));
				} else {
					// icon is empty so we need to pull outerHTML
					var copy_icon = $(icon).clone();
					$(copy_icon).addClass('fa-4x');
					$('#media-icon').append(copy_icon);
				}
				$('#media-item').show();
			});
			wrapper.append(link);
			wrapper.attr('data-location',  script_root + '/files/' + f.location);
			wrapper.attr('data-id',  f.id);
			wrapper.attr('data-filename',  fname);
			list.append(wrapper);
		}
	}

	function insert_at_cursor(editor, text) {
		var doc = editor.getDoc();
		var cursor = doc.getCursor();
		doc.replaceRange(text, cursor);
	}

	function submit_form(){
		editor.save(); // Save the CodeMirror data to the Textarea
		$.ajax({
			type: "POST",
			url: $("#page-edit").attr('action'),
			data: $("#page-edit").serialize(),
			success: function (data) {
				if (data.result == 'success'){
					if (data.operation == 'publish'){
						window.location = script_root + '/admin/pages';
					} else if (data.operation == 'save'){
						$('input[name=id]').val(data.page.id);
						ezal({
							title: 'Saved',
							body: 'Your changes have been saved',
							button: 'Okay'
						});
					}
				}
			}
		});
	}

	function preview_page() {
		editor.save(); // Save the CodeMirror data to the Textarea
		$('#page-edit').attr('action', '{{ request.script_root }}/admin/pages?operation=preview');
		$('#page-edit').attr('target', '_blank');
		$('#page-edit').submit();
	}

	$(document).ready(function () {
		$('#media-insert').click(function (e) {
			var tag = ''
			try {
				var tag = $('#media-icon').children()[0].nodeName.toLowerCase();
			} catch(err) {
				var tag = '';
			}
			var link = $('#media-link').val();
			var fname = $('#media-filename').text();
			if (tag == 'img') {
				var entry = '![{0}]({1})'.format(fname, link);
			} else {
				var entry = '[{0}]({1})'.format(fname, link);
			}
			insert_at_cursor(editor, entry);
		});


		$('#publish-page').click(function (e) {
			e.preventDefault();
			$('#page-edit').attr('action', '{{ request.script_root }}/admin/pages?operation=publish');
			submit_form();
		});

		$('#save-page').click(function (e) {
			e.preventDefault();
			$('#page-edit').attr('action', '{{ request.script_root }}/admin/pages?operation=save');
			submit_form();
		});

		$('#media-button').click(function () {
			$.get(script_root + '/admin/media', function (data) {
				$('#media-library-list').empty();
				refreshfiles(data);
				$('#media-modal').modal();
			});
		});
	});
</script>
{% endblock %}
